package com.qr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qr.constant.Constant;
import com.qr.context.ThreadContext;
import com.qr.dto.UserLoginDTO;
import com.qr.entity.User;
import com.qr.exception.LoginFailedException;
import com.qr.mapper.UserMapper;
import com.qr.properties.WeChatProperties;
import com.qr.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.time.LocalDateTime;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    public static final String WXURL = "https://api.weixin.qq.com/sns/jscode2session";


    public User Login(UserLoginDTO userLoginDTO) {
        log.info("微信登录:{}" + userLoginDTO.getCode());
        URI url = URI.create(
            WXURL +
            "?appid=" +
            weChatProperties.getAppid() +
            "&secret=" +
            weChatProperties.getSecret() +
            "&js_code=" +
            userLoginDTO.getCode() +
            "&grant_type=authorization_code"
        );
        String data = restTemplate.getForObject(url, String.class);
        // JSON字符串转换为JSON对象
        JSONObject jsonObject = JSONObject.parseObject(data);
        // 获取结果中的openid
        String openid = jsonObject.getString("openid");
        if(openid == null) {
            throw new LoginFailedException(Constant.LOGIN_FAILED);
        }

        User user = userMapper.selectByOpenid(openid);
        if(user == null) {
            user = user.builder()
                .openid(openid)
                .createTime(LocalDateTime.now())
                .build();
            userMapper.insert(user);
        }

        return user;
    }

    /**
     * 更新用户信息
     * @param user
     */
    public void updateById(User user) {
        // 根据id更新用户信息
        Long userId = ThreadContext.getCurrentId();
        user.setId(userId);
        userMapper.updateById(user);
    }

    /**
     * 根据id查询用户
     * @return
     */
    public User getById() {
        Long userId = ThreadContext.getCurrentId();
        User user = userMapper.selectById(userId);
        return user;
    }
}
